////package com.zzyl.nursing.job;
////
////import cn.hutool.json.JSONUtil;
////import com.zzyl.framework.config.properties.AliIoTConfigProperties;
////import com.zzyl.nursing.service.IDeviceDataService;
////import org.apache.commons.codec.binary.Base64;
////import org.apache.qpid.jms.JmsConnection;
////import org.apache.qpid.jms.JmsConnectionListener;
////import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
////import org.slf4j.Logger;
////import org.slf4j.LoggerFactory;
////import org.springframework.beans.factory.annotation.Autowired;
////import org.springframework.boot.ApplicationArguments;
////import org.springframework.boot.ApplicationRunner;
////import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
////import org.springframework.stereotype.Component;
////
////import javax.crypto.Mac;
////import javax.crypto.spec.SecretKeySpec;
////import javax.jms.*;
////import javax.naming.Context;
////import javax.naming.InitialContext;
////import java.net.InetAddress;
////import java.net.URI;
////import java.net.UnknownHostException;
////import java.util.ArrayList;
////import java.util.Hashtable;
////import java.util.List;
////
////@Component
////public class AmqpClient implements ApplicationRunner {
////    private final static Logger logger = LoggerFactory.getLogger(AmqpClient.class);
////
////    @Autowired
////    private AliIoTConfigProperties aliIoTConfigProperties;
////
////    //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。
////    //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。
////    private static String clientId;
////
////    static {
////        try {
////            clientId = InetAddress.getLocalHost().getHostAddress();
////        } catch (UnknownHostException e) {
////            e.printStackTrace();
////        }
////    }
////
////    // 指定单个进程启动的连接数
////    // 单个连接消费速率有限，请参考使用限制，最大64个连接
////    // 连接数和消费速率及rebalance相关，建议每500QPS增加一个连接
////    private static int connectionCount = 64;
////
////    //业务处理异步线程池，线程池参数可以根据您的业务特点调整，或者您也可以用其他异步方式处理接收到的消息。
////
////    @Autowired
////    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
////
////    public void start() throws Exception {
////        List<Connection> connections = new ArrayList<>();
////
////        //参数说明，请参见AMQP客户端接入说明文档。
////        for (int i = 0; i < connectionCount; i++) {
////            long timeStamp = System.currentTimeMillis();
////            //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
////            String signMethod = "hmacsha1";
////
////            //userName组装方法，请参见AMQP客户端接入说明文档。
////            String userName = clientId + "-" + i + "|authMode=aksign"
////                    + ",signMethod=" + signMethod
////                    + ",timestamp=" + timeStamp
////                    + ",authId=" + aliIoTConfigProperties.getAccessKeyId()
////                    + ",iotInstanceId=" + aliIoTConfigProperties.getIotInstanceId()
////                    + ",consumerGroupId=" + aliIoTConfigProperties.getConsumerGroupId()
////                    + "|";
////            //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
////            String signContent = "authId=" + aliIoTConfigProperties.getAccessKeyId() + "&timestamp=" + timeStamp;
////            String password = doSign(signContent, aliIoTConfigProperties.getAccessKeySecret(), signMethod);
////            String connectionUrl = "failover:(amqps://" + aliIoTConfigProperties.getHost() + ":5671?amqp.idleTimeout=80000)"
////                    + "?failover.reconnectDelay=30";
////
////            Hashtable<String, String> hashtable = new Hashtable<>();
////            hashtable.put("connectionfactory.SBCF", connectionUrl);
////            hashtable.put("queue.QUEUE", "default");
////            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
////            Context context = new InitialContext(hashtable);
////            ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
////            Destination queue = (Destination) context.lookup("QUEUE");
////            // 创建连接。
////            Connection connection = cf.createConnection(userName, password);
////            connections.add(connection);
////
////            ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);
////            // 创建会话。
////            // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。
////            // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
////            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
////
////            connection.start();
////            // 创建Receiver连接。
////            MessageConsumer consumer = session.createConsumer(queue);
////            consumer.setMessageListener(messageListener);
////        }
////
////        logger.info("amqp  is started successfully, and will exit after server shutdown ");
////    }
////
////    private MessageListener messageListener = message -> {
////        try {
////            //异步处理收到的消息，确保onMessage函数里没有耗时逻辑
////            threadPoolTaskExecutor.submit(() -> processMessage(message));
////        } catch (Exception e) {
////            logger.error("submit task occurs exception ", e);
////        }
////    };
////
////    @Autowired
////    private IDeviceDataService deviceDataService;
////
////    /**
////     * 在这里处理您收到消息后的具体业务逻辑。
////     */
////    private void processMessage(Message message) {
////        try {
////            byte[] body = message.getBody(byte[].class);
////            String contentStr = new String(body);
////            String topic = message.getStringProperty("topic");
////            String messageId = message.getStringProperty("messageId");
////            logger.info("receive message"
////                    + ",\n topic = " + topic
////                    + ",\n messageId = " + messageId
////                    + ",\n content = " + contentStr);
////
////            //把json转换为content
////            Content content = JSONUtil.toBean(contentStr, Content.class);
////            //批量保存
////            deviceDataService.batchInsertDeviceData(content);
////
////        } catch (Exception e) {
////            logger.error("processMessage occurs error ", e);
////        }
////    }
////
////    private JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
////        /**
////         * 连接成功建立。
////         */
////        @Override
////        public void onConnectionEstablished(URI remoteURI) {
////            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
////        }
////
////        /**
////         * 尝试过最大重试次数之后，最终连接失败。
////         * @param error
////         */
////        @Override
////        public void onConnectionFailure(Throwable error) {
////            logger.error("onConnectionFailure, {}", error.getMessage());
////        }
////
////        /**
////         * 连接中断。
////         * @param remoteURI
////         */
////        @Override
////        public void onConnectionInterrupted(URI remoteURI) {
////            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
////        }
////
////        /**
////         * 连接中断后又自动重连上。
////         * @param remoteURI
////         */
////        @Override
////        public void onConnectionRestored(URI remoteURI) {
////            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
////        }
////
////        @Override
////        public void onInboundMessage(JmsInboundMessageDispatch envelope) {
////        }
////
////        @Override
////        public void onSessionClosed(Session session, Throwable cause) {
////        }
////
////        @Override
////        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {
////        }
////
////        @Override
////        public void onProducerClosed(MessageProducer producer, Throwable cause) {
////        }
////    };
////
////    /**
////     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
////     * @param toSignString
////     * @param secret
////     * @param signMethod
////     * @return
////     * @throws Exception
////     */
////    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
////        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
////        Mac mac = Mac.getInstance(signMethod);
////        mac.init(signingKey);
////        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
////        return Base64.encodeBase64String(rawHmac);
////    }
////
////    @Override
////    public void run(ApplicationArguments args) throws Exception {
////        start();
////    }
////}
//
//
//
//
//
//
//
//
//
//
//
//
//
//package com.zzyl.nursing.job;
//
//import cn.hutool.json.JSONUtil;
//import com.zzyl.framework.config.properties.AliIoTConfigProperties;
//import com.zzyl.nursing.service.IDeviceDataService;
//import org.apache.commons.codec.binary.Base64;
//import org.apache.qpid.jms.JmsConnection;
//import org.apache.qpid.jms.JmsConnectionListener;
//import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.ApplicationArguments;
//import org.springframework.boot.ApplicationRunner;
//import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
//import org.springframework.stereotype.Component;
//
//import javax.crypto.Mac;
//import javax.crypto.spec.SecretKeySpec;
//import javax.jms.*;
//import javax.naming.Context;
//import javax.naming.InitialContext;
//import java.net.InetAddress;
//import java.net.URI;
//import java.net.UnknownHostException;
//import java.util.ArrayList;
//import java.util.Hashtable;
//import java.util.List;
//
//// 导入独立的 Content 类
//import com.zzyl.nursing.job.Content;
//
//@Component
//public class AmqpClient implements ApplicationRunner {
//    private final static Logger logger = LoggerFactory.getLogger(AmqpClient.class);
//
//    @Autowired
//    private AliIoTConfigProperties aliIoTConfigProperties;
//
//    // 控制台服务端订阅中消费组状态页客户端 ID 一栏将显示 clientId 参数。
//    // 建议使用机器 UUID、MAC 地址、IP 等唯一标识等作为 clientId。便于您区分识别不同的客户端。
//    private static String clientId;
//
//    static {
//        try {
//            clientId = InetAddress.getLocalHost().getHostAddress();
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        }
//    }
//
//    // 指定单个进程启动的连接数
//    // 单个连接消费速率有限，请参考使用限制，最大 64 个连接
//    // 连接数和消费速率及 rebalance 相关，建议每 500QPS 增加一个连接
//    private static int connectionCount = 64;
//
//    // 业务处理异步线程池，线程池参数可以根据您的业务特点调整，或者您也可以用其他异步方式处理接收到的消息。
//    @Autowired
//    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
//
//    public void start() throws Exception {
//        List<Connection> connections = new ArrayList<>();
//
//        // 参数说明，请参见 AMQP 客户端接入说明文档。
//        for (int i = 0; i < connectionCount; i++) {
//            long timeStamp = System.currentTimeMillis();
//            // 签名方法：支持 hmacmd5、hmacsha1 和 hmacsha256。
//            String signMethod = "hmacsha1";
//
//            // userName 组装方法，请参见 AMQP 客户端接入说明文档。
//            String userName = clientId + "-" + i + "|authMode=aksign"
//                    + ",signMethod=" + signMethod
//                    + ",timestamp=" + timeStamp
//                    + ",authId=" + aliIoTConfigProperties.getAccessKeyId()
//                    + ",iotInstanceId=" + aliIoTConfigProperties.getIotInstanceId()
//                    + ",consumerGroupId=" + aliIoTConfigProperties.getConsumerGroupId()
//                    + "|";
//            // 计算签名，password 组装方法，请参见 AMQP 客户端接入说明文档。
//            String signContent = "authId=" + aliIoTConfigProperties.getAccessKeyId() + "&timestamp=" + timeStamp;
//            String secret = aliIoTConfigProperties.getAccessKeySecret();
//            if (secret == null || signContent == null) {
//                logger.error("AccessKeySecret or signContent is null, cannot generate password.");
//                continue;
//            }
//            String password = doSign(signContent, secret, signMethod);
//            String connectionUrl = "failover:(amqps://" + aliIoTConfigProperties.getHost() + ":5671?amqp.idleTimeout=80000)"
//                    + "?failover.reconnectDelay=30";
//
//            Hashtable<String, String> hashtable = new Hashtable<>();
//            hashtable.put("connectionfactory.SBCF", connectionUrl);
//            hashtable.put("queue.QUEUE", "default");
//            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
//            Context context = new InitialContext(hashtable);
//            ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
//            Destination queue = (Destination) context.lookup("QUEUE");
//            // 创建连接。
//            Connection connection = cf.createConnection(userName, password);
//            connections.add(connection);
//
//            ((JmsConnection) connection).addConnectionListener(myJmsConnectionListener);
//            // 创建会话。
//            // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用 message.acknowledge()。
//            // Session.AUTO_ACKNOWLEDGE: SDK 自动 ACK（推荐）。
//            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//
//            connection.start();
//            // 创建 Receiver 连接。
//            MessageConsumer consumer = session.createConsumer(queue);
//            consumer.setMessageListener(messageListener);
//        }
//
//        logger.info("amqp  is started successfully, and will exit after server shutdown ");
//    }
//
//    private MessageListener messageListener = message -> {
//        try {
//            // 异步处理收到的消息，确保 onMessage 函数里没有耗时逻辑
//            threadPoolTaskExecutor.submit(() -> processMessage(message));
//        } catch (Exception e) {
//            logger.error("submit task occurs exception ", e);
//        }
//    };
//
//    @Autowired
//    private IDeviceDataService deviceDataService;
//
//    /**
//     * 在这里处理您收到消息后的具体业务逻辑。
//     */
//    private void processMessage(Message message) {
//        try {
//            byte[] body = message.getBody(byte[].class);
//            String contentStr = new String(body);
//            String topic = message.getStringProperty("topic");
//            String messageId = message.getStringProperty("messageId");
//            logger.info("receive message"
//                    + ",\n topic = " + topic
//                    + ",\n messageId = " + messageId
//                    + ",\n content = " + contentStr);
//
//            // 把 json 转换为 content
//            Content content = JSONUtil.toBean(contentStr, Content.class);
//            // 批量保存
//            deviceDataService.batchInsertDeviceData(content);
//
//        } catch (Exception e) {
//            logger.error("processMessage occurs error ", e);
//        }
//    }
//
//    private JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
//        /**
//         * 连接成功建立。
//         */
//        @Override
//        public void onConnectionEstablished(URI remoteURI) {
//            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
//        }
//
//        /**
//         * 尝试过最大重试次数之后，最终连接失败。
//         * @param error
//         */
//        @Override
//        public void onConnectionFailure(Throwable error) {
//            logger.error("onConnectionFailure, {}", error.getMessage());
//        }
//
//        /**
//         * 连接中断。
//         * @param remoteURI
//         */
//        @Override
//        public void onConnectionInterrupted(URI remoteURI) {
//            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
//        }
//
//        /**
//         * 连接中断后又自动重连上。
//         * @param remoteURI
//         */
//        @Override
//        public void onConnectionRestored(URI remoteURI) {
//            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
//        }
//
//        @Override
//        public void onInboundMessage(JmsInboundMessageDispatch envelope) {
//        }
//
//        @Override
//        public void onSessionClosed(Session session, Throwable cause) {
//        }
//
//        @Override
//        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {
//        }
//
//        @Override
//        public void onProducerClosed(MessageProducer producer, Throwable cause) {
//        }
//    };
//
//    /**
//     * 计算签名，password 组装方法，请参见 AMQP 客户端接入说明文档。
//     * @param toSignString 需要签名的字符串
//     * @param secret 签名密钥
//     * @param signMethod 签名方法
//     * @return 签名后的字符串
//     * @throws Exception 当签名过程出现异常时抛出
//     */
//    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
//        if (toSignString == null || secret == null || signMethod == null) {
//            throw new IllegalArgumentException("toSignString, secret and signMethod cannot be null");
//        }
//        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
//        Mac mac = Mac.getInstance(signMethod);
//        mac.init(signingKey);
//        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
//        return Base64.encodeBase64String(rawHmac);
//    }
//
//    @Override
//    public void run(ApplicationArguments args) throws Exception {
//        start();
//    }
//}